﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MKAdminCore.Controllers;
using MKAdminCore.DTO.Web.Common;
using MKAdminCore.ToolKit.Config;
using MKAdminCore.ToolKit.ExcelHelper;
using MKAdminCore.ToolKit.DataTableHelper;
using MKAdminCore.IService.Web.TableData;
using MKAdminCore.DTO.Web.TableData.BasicTable;
using MKAdminCore.ToolKit.Extensions;

namespace MKAdminCore.Areas.Excel.Controllers
{
    [Area("Excel")]
    [Route("Excel/[controller]/[action]")]
    public class ExportController : BaseMvcController
    {
        private IBasicTableService _iBasicTableService;

        public ExportController(IBasicTableService iBasicTableService)
        {
            _iBasicTableService = iBasicTableService;
        }

        public IActionResult Index()
        {
            return View(PageViewFilesConfig.ExcelExportIndex);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Export(GetBasicTableListParameter parameter)
        {
            var exportResult = new HttpResponseResult<UploadFileModel>() { Data = new UploadFileModel() };

            parameter.pageIndex = 1;
            parameter.pageSize = 9999999;
            var result = _iBasicTableService.List(parameter);

            if (result != null && result.data != null && result.data.Count > 0)
            {
                //组装导出Excel数据 列名|列宽
                DataTable dtlist = new DataTable();
                dtlist.Columns.Add("编号|10", typeof(int));
                dtlist.Columns.Add("姓名", typeof(string));
                dtlist.Columns.Add("年龄|8", typeof(int));
                dtlist.Columns.Add("学历|10", typeof(string));
                dtlist.Columns.Add("联系方式|20", typeof(string));

                foreach (var item in result.data)
                {
                    dtlist.Rows.Add(item.EmployeeId, item.EmployeeName, item.EmployeeAge
                        , item.Education, item.ContactPhone);
                }
                var catalogConfig = AppSettingConfigExtensions.GetUploadFileConfigInfo("Excel");

                exportResult.Data.catalog = $@"\{ DateTime.Now.ToString("yyyyMM")}\{ DateTime.Now.ToString("yyyyMMdd")}";
                exportResult.Data.fileName = $@"{ Guid.NewGuid().ToString("N")}.xlsx";

                //保存到临时目录下
                string fileCatalog = $@"{ catalogConfig.SavePath }{exportResult.Data.catalog}";
                if (!Directory.Exists(fileCatalog))
                    Directory.CreateDirectory(fileCatalog);

                string filePath = $@"{ fileCatalog}\{exportResult.Data.fileName}";

                ExcelHelper.Save(dtlist, filePath);
            }

            return Ok(exportResult);
        }
    }
}